<script setup>
	import {getCurrentInstance, onBeforeUnmount, onMounted, ref} from "vue";
	import {getToken} from "@/utils/auth";
	import {addArticle, getArticleByKey, updArticle} from "@/api/article/manage";
	import {
		addPosition,
		delPosition,
		getPositionByKey,
		updPosition,
 	} from "@/api/company/position";
	const { proxy } = getCurrentInstance();
	import emitter from "@/utils/mitt";
	
	const props = defineProps({
		rowId: {
			type: [Number, String],
			default: null
		}
	})
	
	const formData = ref({
		id: null,
		name: null,
		sort: null,
		status: 1,
	});
	const rules = ref({
		name: [{required: true, message: '请输入职位名称', trigger: 'change'}],
	});
	
	const getData = async () => {
		const res = await getPositionByKey({id: props.rowId})
		try {
			if(res.code === 200) {
				const {id, name, sort, status} = res.data
				formData.value.name = name
				formData.value.id = id
				formData.value.status = status
				formData.value.sort = sort
				
			}
		}
		catch(e) {
			console.log(e);
		}
	}
	
	const submit = () => {
		proxy.$refs.elForm.validate(async valid => {
			if(valid) {
				const params = formData.value
				let res
				params.id !== null && params !== '' ? res = await updPosition(params) : res = await addPosition(params)
				try {
					if(res.code === 200) {
						proxy.$modal.msgSuccess('操作成功')
						cancel(true)
					}
					else {
						proxy.$modal.msgError(res.msg)
					}
				}
				catch(e) {
					console.log(e);
					proxy.$modal.msgError(JSON.stringify(e))
				}
			}
		})
	}
	
	const cancel = (ifSubmit = false) => {
		emitter.emit('closeEdit', ifSubmit)
	}
	
	onMounted(() => {
		if(props.rowId) {
			getData();
		}
	})
	
</script>

<template>
	<div class="dialogContent">
		<el-form ref="elForm" :model="formData" :rules="rules" label-width="100px" :size="'default'">
			<el-form-item label="职位名称" prop="name">
				<el-input v-model="formData.name" :style="{ width: '100%' }" clearable placeholder="请输入职位名称"></el-input>
			</el-form-item>
			<el-form-item label="排序值" prop="sort">
				<el-input-number v-model="formData.sort" clearable placeholder="排序值" :step="1" :min="0"></el-input-number>&nbsp;&nbsp;排序值越小越靠前
			</el-form-item>
			<el-form-item label="是否可用" prop="status">
				<el-switch v-model="formData.status" :active-value="1" :inactive-value="0" active-text="可用" inactive-text="不可用"></el-switch>
			</el-form-item>
		</el-form>
		<div class="buttonList">
			<el-button class="button" type="primary" @click="submit">提交</el-button>
			<el-button class="button" @click="cancel">取消</el-button>
		</div>
	</div>
</template>

<style lang="scss" scoped>
	.dialogContent {
		overflow: auto;
	}
	.buttonList {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}
</style>
